package com.jt.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    //1.新增cookie
    public static void addCookie(String name, String value, String path, String domain, Integer maxAge, HttpServletResponse response){
        //if (name==null&&value.length()>0&&value==null&&path==null&&path.length()>0&&domain==null&&domain.length()>0&&maxAge>-1){
        Cookie cookie = new Cookie(name,value);
        cookie.setMaxAge(maxAge);
        cookie.setPath(path);
        cookie.setDomain(domain);
        response.addCookie(cookie);
        //}
    }

    //2.删除cookie
    public static void deleteCookie(String name, String path, String domain, HttpServletResponse response){
        //if (name==null&&value.length()>0&&value==null&&path==null&&path.length()>0&&domain==null&&domain.length()>0&&maxAge>-1){
        Cookie cookie = new Cookie(name,"");
        cookie.setMaxAge(0);
        cookie.setPath(path);
        cookie.setDomain(domain);
        response.addCookie(cookie);
        //}
    }

    //3.根据cookie名称获取cookie对象
    public static Cookie getCookieName(String name, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length>0){
            for (Cookie cook : cookies) {
                if (cook.getName().equalsIgnoreCase(name)){
                    return cook;
                }
            }
        }
        return null;
    }
}
